package ctm.javacode;

import java.io.* ;
import java.sql.*;
import java.util.Properties;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@WebServlet("/sendPW.do") 

public class sendPW extends HttpServlet {
	
	private final String SUCCESS_VIEW = "index.jsp"; 
	private final String ERROR_VIEW = "noUserError.html"; 
	
	private String mail = "";
	private String pw = "";
	
	private final String MAILHOST = "smtp.gmail.com";
	private final String MAILPORT = "465";
	private final String SERVER = "pllabictm@gmail.com";
	private final String PW = "891216aa";
	private Properties props ;
	
	protected void doPost(HttpServletRequest request,
								HttpServletResponse response )
								throws ServletException, IOException {
		
		String ac = request.getParameter("ac");
		mail = request.getParameter("email");
		
		try {
			if (checkAccount(ac))
			{
				props = new Properties();
				props.put("mail.smtp.host", MAILHOST );
				props.setProperty("mail.smtp.socketFactory.class",
						"javax.net.ssl.SSLSocketFactory");
				props.setProperty("mail.smtp.socketFactory.fallback", "false");
				props.setProperty("mail.smtp.port", MAILPORT);
				props.setProperty("mail.smtp.auth", "true");
				
				
				Session session = Session.getDefaultInstance(props, 
							new Authenticator() {
								protected PasswordAuthentication getPasswordAuthentication() {
									return new PasswordAuthentication(SERVER, PW);
								}
					});
				
				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(SERVER));
				message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail));
				message.setSubject("中醫問卷系統密碼信");
				message.setText("您的密碼:" + pw );
				Transport.send(message);
				
				response.sendRedirect(SUCCESS_VIEW);		
			} // end if
			else
			{
				response.sendRedirect(ERROR_VIEW);
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		} // end else	
 catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AddressException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (MessagingException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
	} // end doPost()
	
	
	private boolean checkAccount(String username) throws SQLException, NamingException {
		
		Boolean isUser = false ;
		DbBean db = new DbBean("jdbc/ctmpllab") ;
		ResultSet rs ;
		String newPW = "";

        
		if (db.isConnectedOK()) {		
			try {
				rs = db.ExcuteResult("SELECT * FROM ACCOUNTABLE");		    
			} catch(SQLException e) {
				throw new SQLException(e) ;
			} // end try-catch
			
			while ( rs.next() ) {
				if (rs.getString("account").trim().equals(username)
						&& rs.getString("mail").trim().equals(mail) ) {
					isUser = true ;
					pw = NewPW.GeneratePW();
					newPW = MD5encrypt.generate(pw);//用md5加密帳戶密碼
					String sqlQuery = "UPDATE ACCOUNTABLE SET PASSWORD = '" + newPW + "' WHERE ACCOUNT = '" + username + "'";
					
					db.ExcuteUpdate(sqlQuery);	      
				} // end if
			} // end while
			db.CloseConn() ; // 資料庫關閉
		} // end if
		
		return isUser ;
	} // end checkLogin()

	
} // end class login()





